﻿using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using System;
using System.IO;

namespace Ycjw.PipeLine.Commons.SerializeHelper
{
    /// <summary>
    /// 通用Json的序列化和反序列化
    /// </summary>
    public class JsonHepler
    {
        private JsonHepler()
        {
        }

        /// <summary>
        /// 序列化为字符串
        /// </summary>
        /// <param name="obj">需序列化的对象</param>
        /// <returns></returns>
        public static string Json_SerializeObject(object obj)
        {
            return Json_SerializeObject(obj, false);
        }

        /// <summary>
        /// 带格式化的序列化
        /// </summary>
        /// <param name="obj">需序列化的对象</param>
        /// <param name="isTimeFommat">是否时间格式化</param>
        /// <returns></returns>
        public static string Json_SerializeObject(object obj, bool isTimeFommat)
        {
            try
            {
                if (isTimeFommat)
                {
                    var aIsoDateTimeConverter = new IsoDateTimeConverter
                    {
                        DateTimeFormat = "yyyy-MM-dd HH:mm:ss"
                    };
                    return JsonConvert.SerializeObject(obj, Formatting.Indented, aIsoDateTimeConverter);
                }
                else
                {
                    JsonSerializerSettings jsonSettings = new JsonSerializerSettings
                    {
                        DefaultValueHandling = DefaultValueHandling.Ignore,
                        NullValueHandling = NullValueHandling.Ignore,
                        ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore,
                        TypeNameHandling = TypeNameHandling.Auto,
                        MissingMemberHandling = MissingMemberHandling.Ignore,
                        ObjectCreationHandling = ObjectCreationHandling.Reuse,
                        PreserveReferencesHandling = PreserveReferencesHandling.None,
                        MetadataPropertyHandling = MetadataPropertyHandling.Ignore,
                        TypeNameAssemblyFormatHandling = TypeNameAssemblyFormatHandling.Simple,
                        ConstructorHandling = ConstructorHandling.Default
                    };
                    return JsonConvert.SerializeObject(obj, Formatting.Indented, jsonSettings);
                }
            }
            catch (Exception ex)
            {
                LogHelper.Error(ex);
                return string.Empty;
            }
        }

        /// <summary>
        /// 反序列化为指定对象
        /// </summary>
        /// <typeparam name="T">反序列化的对象类型</typeparam>
        /// <param name="strSerializeJson">对象的Json字符串</param>
        /// <returns></returns>
        public static T Json_DeserializeObject<T>(string strSerializeJson) where T : class
        {
            try
            {
                return (T)JsonConvert.DeserializeObject(strSerializeJson, typeof(T));
            }
            catch (Exception ex)
            {
                LogHelper.Error(ex);
                return default(T);
            }
        }

        /// <summary>
        /// 反序列化为指定对象
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="strSerializeJson"></param>
        /// <returns></returns>
        public static T Json_Deserialize<T>(string strSerializeJson)
        {
            try
            {
                return (T)JsonConvert.DeserializeObject(strSerializeJson, typeof(T));
            }
            catch (Exception ex)
            {
                LogHelper.Error(ex);
                return default(T);
            }
        }

        /// <summary>
        /// 序列化为Xml字符串
        /// </summary>
        /// <param name="obj">需序列化的对象</param>
        /// <returns></returns>
        public static string Json_SerializeObject_Xml(object obj)
        {
            string jsonData = Json_SerializeObject(obj, true);
            try
            {
                return JsonConvert.DeserializeXmlNode(jsonData).InnerXml.ToString();
            }
            catch (Exception ex)
            {
                LogHelper.Error(ex);
                return string.Empty;
            }
        }

        /// <summary>
        /// Xml节点序列化为指定对象
        /// </summary>
        /// <typeparam name="T">反序列化的对象类型</typeparam>
        /// <param name="xmlNode">Xml的节点</param>
        /// <returns></returns>
        public static T Json_DeserializeObject_Xml<T>(System.Xml.XmlNode xmlNode) where T : class
        {
            string jsonData;
            try
            {
                jsonData = JsonConvert.SerializeXmlNode(xmlNode);
            }
            catch (Exception ex)
            {
                LogHelper.Error(ex);
                return default(T);
            }
            return Json_DeserializeObject<T>(jsonData);
        }

        /// <summary>
        /// 序列化为文件
        /// </summary>
        /// <param name="path">序列化的文件名称:全路径</param>
        /// <param name="info">需序列化的对象</param>
        /// <returns></returns>
        public static bool SaveObjectInfoToFile(string path, object info)
        {
            using (StreamWriter sw = new StreamWriter(path))
            {
                try
                {
                    JsonSerializer serializer = new JsonSerializer();
                    JsonWriter writer = new JsonTextWriter(sw);
                    serializer.Serialize(writer, info);
                    writer.Close();
                    sw.Close();
                    return true;
                }
                catch
                {
                    return false;
                }
                finally
                {
                    sw.Close();
                }
            }
        }

        /// <summary>
        /// 反序列化为对象
        /// </summary>
        /// <typeparam name="T">反序列化的对象类型</typeparam>
        /// <param name="path">序列化的文件名称:全路径</param>
        /// <returns></returns>
        public static T GetObjectInfoFromFile<T>(string path)
        {
            using (StreamReader sr = new StreamReader(path))
            {
                try
                {
                    JsonSerializer serializer = new JsonSerializer();
                    JsonReader reader = new JsonTextReader(sr);
                    return serializer.Deserialize<T>(reader);
                }
                catch(Exception ex)
                {
                    LogHelper.Error(ex.Message);
                    return default(T);
                }
                finally
                {
                    sr.Close();
                }
            }
        }

        /// <summary>
        /// JSon串转为对象
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="infoJson">Json串</param>
        /// <param name="type">对象类型</param>
        /// <returns></returns>
        public static T GetObjectType<T>(string infoJson, Type type)
        {
            try
            {
                var data = Commons.SerializeHelper.JsonHepler.Json_DeserializeObject<Object>(infoJson);
                JsonSerializer serializer = new JsonSerializer();
                string jsonValue = JsonHepler.Json_SerializeObject(data, true);
                return (T)serializer.Deserialize(new JsonTextReader(new StringReader(jsonValue)), type);
            }
            catch
            {
                return default(T);
            }
        }
    }
}